<template>
	<view>
		<!-- #ifdef MP-WEIXIN -->
		<view style="position: fixed;top: 0upx;left: 0;right: 0;z-index: 99;">
		<!-- #endif -->
			<!-- #ifdef H5 -->
			<view style="position: fixed;top: 0upx;left: 0;right: 0;z-index: 99;">
			<!-- #endif -->
				<!-- #ifdef APP -->
				<view
					style="position: fixed;top: 0upx;left: 0;right: 0;z-index: 99;padding-top: 120upx;background: #FFFFFF;">
				<!-- #endif -->
					<ren-dropdown-filter v-if="isShow" :filterData='filterData' :border="false"
						:defaultIndex='defaultIndex' @onSelected='change' class="u-skeleton-rect"
						@dateChange="dateChange">
					</ren-dropdown-filter>
				</view>
				<!-- #ifdef APP -->
				<view style="margin-top: 220upx;">
				<!-- #endif -->
					<!-- #ifndef APP -->
					<view style="margin-top: 100upx;">
					<!-- #endif -->
						<view class="margin-lr-sm margin-top-16 padding bg radius" v-for="(item,index) in orderList"
							:key='index' @click="goOrder(item.ordersId)" v-if="item.appointInformation">
							<view class="text-lg text-bold flex justify-between" style="align-items: flex-start;"
								v-if="item.appointInformation">
								<text style="width: 60%;">
									{{item.appointInformation?item.appointInformation.serviceName:''}}{{item.appointInformation?item.appointInformation.hospitalName:''}}订单
								</text>
								<text
									style="font-size: 24rpx;color: #999999;margin-top: 10rpx;font-weight: 500;">{{item.createTime}}</text>
							</view>
							<view class="margin-top-xs" style="font-size: 24upx;"><text
									style="color: #999999;">地址：</text>{{item.appointInformation?item.appointInformation.hospitalName:''}}
							</view>
							<view class="margin-top-xs" style="font-size: 24upx;"><text
									style="color: #999999;">预约时间：</text>
								<text style="font-weight: bold;font-size: 26upx;">
									{{item.appointInformation?item.appointInformation.hopeTime:''}}
								</text>

							</view>
							<view class="margin-tb-sm" style="width: 100%;height: 1rpx;background: #F2F2F2;"></view>
							<view class="flex align-center justify-between">
								<view class=" text-30 text-bold" style="color: #468EF8;">
									￥{{item.payMoney}}
								</view>
								<view class="text-sm boxbtn" @click.stop="takeOrder(item)">接单</view>
							</view>
						</view>
					</view>


					<empty v-if="orderList.length==0"></empty>
					<view v-if="goback==true" class="goback" @click="gotoBack">
						<image style="width: 88rpx;height: 88rpx;border-radius: 50%;"
							src="../../static/images/goback.png" mode=""></image>
					</view>
				</view>
</template>

<script>
	import empty from '../../components/empty.vue'
	export default {
		components: {
			empty
		},
		data() {
			return {
				isShow: false,
				page: 1,
				limit: 10,
				orderList: [],

				userId: '',

				latitude: '',
				longitude: '',
				token: '',
				defaultIndex: [0, 0, 0],
				filterData: [
					[{
							label: '最新发布',
							value: '',
						}, {
							label: '从远到近',
							value: '1',
						},
						{
							label: '从近到远',
							value: '2',
						}
					],
					[{
						label: '全部医院',
						value: '',
					}],
					[{
							label: '最新预约',
							value: '',
						},
						{
							label: '从远到近',
							value: '1',
						},
						{
							label: '从近到远',
							value: '2',
						}
					],
				],
				createTime: '2',
				distance: '',
				hospitalName: '',
				hopeTime: '',
				goback: false,
				arr: [],
				showModal: true,
				geRen: 0,
				shopState: false,
			}

		},
		onPageScroll(e) {
			if (e.scrollTop > 350) {
				this.goback = true
			} else {
				this.goback = false
			}
		},
		onLoad() {
			let that = this

			that.token = this.$queue.getData('token');
			if (that.token) {

				uni.getLocation({
					type: 'gcj02',
					geocode: true, //设置该参数为true可直接获取经纬度及城市信息
					success: function(res) {
						console.log(res, '地理位置')
						that.latitude = res.latitude
						that.longitude = res.longitude
						that.page = 1
						that.geRen = uni.getStorageSync("geRen")
						if (that.geRen == 2) {
							that.getyiyuanList();
							that.getorderlist(that.latitude, that.longitude)
						}
					},
					fail: function(err) {
						console.log(err, '获取地址失败')
					}
				})
				setInterval(function() {
					// that.orderList=[]
					that.geRen = uni.getStorageSync("geRen")
					if (that.geRen == 2) {
						that.page = 1
						that.getorderlist(that.latitude, that.longitude)
					}
				}, 10000 * 1000) // 修改时间 +++++++++++++++++++ 原 10000
			} else {
				uni.showModal({
					title: '提示',
					content: '您还未登录,请先登录',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							uni.navigateTo({
								url: '/pages/public/login'
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			}
		},
		onShow() {
			if (uni.getStorageSync('shopState') === 0 || !uni.getStorageSync('shopState')) {
				this.shopState = false
			} else {
				this.shopState = true
			}
			console.log(uni.getStorageSync('shopState'), 'aaaaaaa')
			this.token = this.$queue.getData('token');
			// let jiedan = this.$queue.getData('jiedan');
			if (this.token) {
				this.getUserInfo()
				// #ifdef MP-WEIXIN
				//订阅
				this.$Request.getT('/app/common/type/312').then(res => { //订单变更通知 312
					if (res.code == 0) {
						if (res.data && res.data.value) {
							this.arr.push(res.data.value)
						}
					}
				})

				this.$Request.getT('/app/common/type/352').then(res => { //绑定通知 352
					if (res.code == 0) {
						if (res.data && res.data.value) {
							this.arr.push(res.data.value)
						}
					}
				})





				if (this.showModal) {
					this.openMsg()
				}
				// #endif
				this.getwz()

			} else {
				uni.showModal({
					title: '提示',
					content: '您还未登录,请先登录',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							uni.navigateTo({
								url: '/pages/public/login'
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
				this.orderList = []
			}

			// this.getGameList()
		},
		methods: {
			openMsg() {
				console.log('订阅消息')
				var that = this
				uni.getSetting({
					withSubscriptions: true, //是否获取用户订阅消息的订阅状态，默认false不返回
					success(ret) {
						console.log(ret.subscriptionsSetting, '------------------')
						// if (ret.subscriptionsSetting.itemSettings && Object.keys(ret.subscriptionsSetting.itemSettings).length == 2) {
						if (ret.subscriptionsSetting.itemSettings) {
							uni.setStorageSync('sendMsg', true)
							uni.openSetting({ // 打开设置页 
								success(rea) {
									console.log(rea.authSetting)
								}
							});
						} else { // 用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息
							console.log(99999)
							uni.setStorageSync('sendMsg', false)
							uni.showModal({
								title: '提示',
								content: '为了更好的体验,请绑定消息推送',
								confirmText: '确定',
								cancelText: '取消',
								success: function(res) {
									if (res.confirm) {
										uni.requestSubscribeMessage({
											tmplIds: that.arr,
											success(re) {
												console.log(JSON.stringify(re),
													'++++++++++++++')
												var datas = JSON.stringify(re);
												if (datas.indexOf("accept") != -1) {
													console.log(re)
													// uni.setStorageSync('sendMsg', true)
												}
											},
											fail: (res) => {
												console.log(res)
											}
										})
										// uni.setStorageSync('sendMsg', true)
										console.log('确认')
										that.showModal = false
									} else if (res.cancel) {
										console.log('取消')
										// uni.setStorageSync('sendMsg', false)
										that.showModal = true
									}
								}
							})
						}
					}
				})
			},
			getyiyuanList() {
				let data = {
					lat: this.latitude,
					lng: this.longitude
				}
				this.$Request.get('/app/Login/selectCity', data).then(ret => {
					if (ret.code == 0) {
						this.$Request.get("/app/hospital/getHospitalList", {
							city: ret.data.city
						}).then(res => {
							if (res.code == 0) {
								this.filterData[1] = [{
									label: '全部医院',
									value: '',
								}]
								res.data.records.map(item => {
									let obj = {
										label: item.hospitalName,
										value: item.hospitalName,
									}
									this.filterData[1].push(obj)
								})
								this.isShow = true
								console.log(this.filterData, '*****************')
							}
						});
					} else {
						uni.showToast({
							title: '获取城市失败请重试！',
							icon: 'none'
						})
					}
				})
			},
			//回到顶部
			gotoBack() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				})
			},
			// 筛选
			change(e) {
				console.log(e)
				this.createTime = e[0][0].value
				this.hospitalName = e[1][0].value
				this.hopeTime = e[2][0].value
				this.page = 1
				if (this.geRen == 2) {
					this.getorderlist()
				}
			},
			// 获取当前经纬度
			getwz() {
				let that = this
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						that.latitude = res.latitude
						that.longitude = res.longitude
						that.page = 1
						if (that.geRen == 2) {
							that.getyiyuanList();
							that.getorderlist(that.latitude, that.longitude)
						}
					}
				});
			},
			getUserInfo() {
				this.$Request.get("/app/user/selectUserById").then(res => {
					if (res.code == 0) {
						uni.setStorageSync('rate', res.data.rate)
					}
				});
			},
			getorderlist(latitude, longitude, sort) {
				let data = {
					page: this.page,
					limit: this.limit,
					latitude: this.latitude,
					longitude: this.longitude,
					createTime: this.createTime,
					hospitalName: this.hospitalName,
					hopeTime: this.hopeTime,
					// sort: this.value3
					shopId: uni.getStorageSync('shopId') || ""
				}
				this.$Request.get("/app/orders/errandGetOrderList", data).then(res => {
					uni.stopPullDownRefresh();
					if (res.code == 0) {
						if (res.data) {
							let rate = uni.getStorageSync('rate')
							if (this.page == 1) {
								res.data.records.forEach(d => {
									d.payMoney = parseFloat(parseFloat(d.payMoney) * parseFloat(rate))
										.toFixed(2);
								});
								this.orderList = res.data.records
							} else {
								res.data.records.forEach(d => {
									d.payMoney = parseFloat(parseFloat(d.payMoney) * parseFloat(rate))
										.toFixed(2);
								});
								this.orderList = [...this.orderList, ...res.data.records]
							}
							this.$queue.remove('jiedan')
						}

					}
				});
			},
			//跳转详情
			goOrder(id) {
				if (!uni.getStorageSync('token')) {
					uni.showModal({
						title: '提示',
						content: '您还未登录,请先登录',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.navigateTo({
									url: '/pages/public/login'
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
					return
				}
				let that = this
				if (uni.getStorageSync('sendMsg')) {
					console.log('授权+1')
					uni.requestSubscribeMessage({
						tmplIds: that.arr,
						success(re) {
							console.log(JSON.stringify(re), 111111111111)
							var datas = JSON.stringify(re);
							if (datas.indexOf("accept") != -1) {
								// console.log(re)
							}
						},
						fail: (res) => {
							// console.log(res)
						}
					})
				}
				uni.navigateTo({
					url: '/my/order/pay?id=' + id + '&name=接单详情'
				})

			},
			//接单

			takeOrder(e) {
				if (!uni.getStorageSync('token')) {
					uni.showModal({
						title: '提示',
						content: '您还未登录,请先登录',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.navigateTo({
									url: '/pages/public/login'
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
					return
				}
				if (!this.shopState) {
					uni.showModal({
						title: '提示',
						content: '您的接单状态为离线，请上线后操作',
						showCancel: false
					})
					return
				}
				let that = this
				uni.showModal({
					title: '提示',
					content: '确定接单吗？',
					success: function(res) {
						if (res.confirm) {
							// console.log('用户点击确定');
							let data = {
								ordersId: e.ordersId
							}
							that.$Request.post("/app/orders/insertMyOrders", data).then(ret => {
								if (ret.code == 0) {
									uni.showToast({
										title: '接单成功',
										icon: 'none'
									})
									setTimeout(function() {
										that.page = 1
										that.getorderlist()
										uni.switchTab({
											url: '/pages/order/index'
										})
									}, 1000);
								} else {
									uni.showToast({
										title: ret.msg,
										icon: 'none'
									})
								}
							});
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				});
			}
		},
		onReachBottom: function() {
			if (this.geRen == 2) {
				this.page = this.page + 1;
				this.getorderlist()
			}
		},
		onPullDownRefresh: function() {
			if (this.geRen == 2) {
				this.page = 1;
				this.getorderlist()
			} else {
				uni.stopPullDownRefresh()
			}
		},
	}
</script>

<style>
	page {
		background: #F2F2F2;
	}

	.goback {
		position: fixed;
		top: 80%;
		right: 30rpx;
	}

	.bg {
		background: #FFFFFF;
	}

	.box {
		flex: 1;
		text-align: center;
	}

	.active {
		/* background: #F2F5FF; */
		color: #557EFD;
	}



	.btn {
		background-color: #557EFD;
		border-radius: 5upx;
		width: 100%;
		color: #FFFFFF;
		text-align: center;
		padding: 20upx 0;
	}

	.boxbtn {
		background: #468EF8;
		color: #FFFFFF;
		padding: 12upx 45rpx;
		border-radius: 45rpx;
	}
</style>